<?php

namespace App\Listeners;

use App\Events\Upload;
use App\Models\FileTransaction;
use App\Tyt\Manager\Storage\StorageManager;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;

class SendUpload implements ShouldQueue
{
    use InteractsWithQueue;

    /**
     * 队列化任务使用的连接名称。
     *
     * @var string|null
     */
    public $connection = 'redis';

    /**
     * 队列化任务使用的队列名称。
     *
     * @var string|null
     */
    public $queue = 'upload';

    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param Upload $event
     * @return void
     */
    public function handle(Upload $event)
    {
        $files = FileTransaction::find($event->transaction->id);
        $config = $files->config;
        if (!$files->is_upload && $config) {
            $storage = new StorageManager();
            $path = \Storage::path($files->file_path);
            \Log::debug('data upload file', ['data' => $path]);
            $storage = $storage->init($config)->setParams([
                'name' => $storage->setName($files),
                'path' => $path
            ])->send();
            $data = $storage->getData();
            \Log::debug('data upload file', ['data' => $data]);
            if ($storage->isSuccess()) {
                $files->name = $data['key'];
                $files->is_upload = $storage->isSuccess();
                $files->save();
            }
        }
    }
}
